using Prism.Mvvm;
using Prism.Commands;
using LiveCharts;
using LiveCharts.Wpf;
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using SanmaoTools.Common.Untils;
using SanmaoTools.Models;
using System.Windows.Media;
using Prism.Regions;

namespace Tryit.ViewModels
{
    public class CurveAnalysisViewModel : BindableBase, INavigationAware
    {
        private SeriesCollection _seriesCollection = new SeriesCollection();
        public SeriesCollection SeriesCollection
        {
            get => _seriesCollection;
            set => SetProperty(ref _seriesCollection, value);
        }

        private string[] _labels;
        public string[] Labels
        {
            get => _labels;
            set => SetProperty(ref _labels, value);
        }

        private Func<double, string> _yFormatter;
        public Func<double, string> YFormatter
        {
            get => _yFormatter;
            set => SetProperty(ref _yFormatter, value);
        }

        private ObservableCollection<string> _elementList;
        public ObservableCollection<string> ElementList
        {
            get => _elementList;
            set => SetProperty(ref _elementList, value);
        }

        private string _selectedElement;
        public string SelectedElement
        {
            get => _selectedElement;
            set
            {
                if (SetProperty(ref _selectedElement, value))
                {
                    UpdateChart();
                }
            }
        }

        private DateTime? _startDate;
        public DateTime? StartDate
        {
            get => _startDate;
            set
            {
                if (SetProperty(ref _startDate, value))
                {
                    UpdateChart();
                }
            }
        }

        private DateTime? _endDate;
        public DateTime? EndDate
        {
            get => _endDate;
            set
            {
                if (SetProperty(ref _endDate, value))
                {
                    UpdateChart();
                }
            }
        }

        private ObservableCollection<string> _brandList;
        public ObservableCollection<string> BrandList
        {
            get => _brandList;
            set => SetProperty(ref _brandList, value);
        }

        private string _selectedBrand;
        public string SelectedBrand
        {
            get => _selectedBrand;
            set
            {
                if (SetProperty(ref _selectedBrand, value))
                {
                    UpdateChart();
                }
            }
        }

        private double _maxValue;
        public double MaxValue
        {
            get => _maxValue;
            set => SetProperty(ref _maxValue, value);
        }

        private double _minValue;
        public double MinValue
        {
            get => _minValue;
            set => SetProperty(ref _minValue, value);
        }

        private double _averageValue;
        public double AverageValue
        {
            get => _averageValue;
            set => SetProperty(ref _averageValue, value);
        }

        public DelegateCommand ClearFilterCommand { get; }

        public CurveAnalysisViewModel()
        {
            _seriesCollection = new SeriesCollection();
            ElementList = new ObservableCollection<string>
            {
                "Si", "Fe", "Cu", "Mn", "Mg", "Cr", "Ni", "Zn", "Ti", "Be", "Ca", "Co", "Ga", "Na", "P", "Pb", "Sb", "Sn", "Sr", "V", "Zr"
            };
            BrandList = new ObservableCollection<string>();
            YFormatter = value => value.ToString("F5") + "%";

            ClearFilterCommand = new DelegateCommand(() =>
            {
                StartDate = null;
                EndDate = null;
                UpdateChart();
            });

            // 先加载牌号列表
            LoadBrandList();

            // 最后设置默认选择Fe元素，这样会触发UpdateChart
            _selectedElement = "Fe";
            _selectedBrand = BrandList[BrandList.Count - 1];
            RaisePropertyChanged(nameof(SelectedElement));
            UpdateChart();
        }

        private void LoadBrandList()
        {
            try
            {
                using (var db = new SqlSugarHelper().GetInstance())
                {
                    var brands = db.Queryable<BrandAndStoveNumber>()
                        .Select(it => it.Name)
                        .ToList();

                    BrandList.Clear();
                    BrandList.Add("全部");
                    foreach (var brand in brands)
                    {
                        BrandList.Add(brand);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载牌号列表失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void UpdateChart()
        {
            try
            {
                if (_seriesCollection == null)
                {
                    _seriesCollection = new SeriesCollection();
                }

                using (var db = new SqlSugarHelper().GetInstance())
                {
                    var query = db.Queryable<Element>();

                    // 应用日期筛选
                    if (StartDate.HasValue)
                    {
                        query = query.Where(it => it.Date >= StartDate.Value);
                    }
                    if (EndDate.HasValue)
                    {
                        query = query.Where(it => it.Date <= EndDate.Value.AddDays(1).AddSeconds(-1));
                    }

                    // 应用牌号筛选
                    if (!string.IsNullOrEmpty(SelectedBrand) && SelectedBrand != "全部")
                    {
                        query = query.Where(it => it.Brand == SelectedBrand);
                    }

                    var elements = query.OrderBy(it => it.Date).ToList();

                    if (!elements.Any())
                    {
                        _seriesCollection.Clear();
                        Labels = new string[0];
                        return;
                    }

                    // 更新X轴标签（日期+牌号+中转包次号）
                    Labels = elements.Select(e =>
                    {
                        var dateStr = e.Date?.ToString("yy-MM-dd HH:mm") ?? "未知日期";
                        var brandStr = !string.IsNullOrEmpty(e.Brand) ? e.Brand : "未知牌号";
                        var transferStr = !string.IsNullOrEmpty(e.Transfernumber) ? e.Transfernumber : "未知批次";
                        return $"{dateStr}\n{brandStr}-{transferStr}";
                    }).ToArray();

                    // 更新数据系列
                    _seriesCollection.Clear();

                    if (!string.IsNullOrEmpty(SelectedElement))
                    {
                        var values = elements.Select(e => GetElementValue(e, SelectedElement)).ToList();

                        // 计算统计值
                        if (values.Any())
                        {
                            MaxValue = values.Max();
                            MinValue = values.Min();
                            AverageValue = values.Average();

                            // 添加主数据系列
                            var mainSeries = new LineSeries
                            {
                                Title = SelectedElement,
                                Values = new ChartValues<double>(values),
                                PointGeometry = DefaultGeometries.Circle,
                                PointGeometrySize = 8,
                                LineSmoothness = 0.5,
                                StrokeThickness = 2
                            };
                            _seriesCollection.Add(mainSeries);

                            // 添加最大值线
                            var maxSeries = new LineSeries
                            {
                                Title = $"最大值: {MaxValue:F3}%",
                                Values = new ChartValues<double>(Enumerable.Repeat(MaxValue, values.Count)),
                                PointGeometry = null,
                                StrokeThickness = 2,
                                Fill = Brushes.Transparent,
                                Stroke = Brushes.Red,
                                LineSmoothness = 0,
                                StrokeDashArray = new DoubleCollection { 0, 1000 }
                            };
                            _seriesCollection.Add(maxSeries);

                            // 添加最小值线
                            var minSeries = new LineSeries
                            {
                                Title = $"最小值: {MinValue:F3}%",
                                Values = new ChartValues<double>(Enumerable.Repeat(MinValue, values.Count)),
                                PointGeometry = null,
                                StrokeThickness = 2,
                                Fill = Brushes.Transparent,
                                Stroke = Brushes.Green,
                                LineSmoothness = 0,
                                StrokeDashArray = new DoubleCollection { 0, 1000 }
                            };
                            _seriesCollection.Add(minSeries);

                            // 添加平均值线
                            var avgSeries = new LineSeries
                            {
                                Title = $"平均值: {AverageValue:F3}%",
                                Values = new ChartValues<double>(Enumerable.Repeat(AverageValue, values.Count)),
                                PointGeometry = null,
                                StrokeThickness = 2,
                                Fill = Brushes.Transparent,
                                Stroke = Brushes.Blue,
                                LineSmoothness = 0,
                                StrokeDashArray = new DoubleCollection { 0, 1000 }
                            };
                            _seriesCollection.Add(avgSeries);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"更新图表失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private double GetElementValue(Element element, string elementName)
        {
            if (element == null || string.IsNullOrEmpty(elementName))
            {
                return 0;
            }

            try
            {
                var property = element.GetType().GetProperty(elementName);
                if (property != null)
                {
                    var value = property.GetValue(element)?.ToString();
                    if (!string.IsNullOrEmpty(value))
                    {
                        // 移除百分号并尝试解析数值
                        value = value.Replace("%", "").Trim();
                        if (double.TryParse(value, out double result))
                        {
                            return result;
                        }
                    }
                }
            }
            catch (Exception)
            {
                // 如果发生任何异常，返回0
                return 0;
            }

            return 0;
        }

        void INavigationAware.OnNavigatedTo(NavigationContext navigationContext)
        {
            return;
        }

        bool INavigationAware.IsNavigationTarget(NavigationContext navigationContext)
        {
            // 先加载牌号列表
            LoadBrandList();

            // 最后设置默认选择Fe元素，这样会触发UpdateChart
            _selectedElement = "Fe";
            _selectedBrand = BrandList[BrandList.Count - 1];
            RaisePropertyChanged(nameof(SelectedElement));
            UpdateChart();
            return false;
        }

        void INavigationAware.OnNavigatedFrom(NavigationContext navigationContext)
        {
            return;
        }
    }
}